package io.geekidea.boot.business.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.geekidea.boot.business.entity.HazardUnit;
import io.geekidea.boot.framework.exception.BusinessException;
import io.geekidea.boot.framework.page.OrderByItem;
import io.geekidea.boot.framework.page.OrderMapping;
import io.geekidea.boot.framework.page.Paging;
import io.geekidea.boot.business.dto.HazardUnitDto;
import io.geekidea.boot.business.mapper.HazardUnitMapper;
import io.geekidea.boot.business.query.HazardUnitQuery;
import io.geekidea.boot.business.service.HazardUnitService;
import io.geekidea.boot.business.vo.HazardUnitVo;
import io.geekidea.boot.util.PagingUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.List;

/**
 * 设备安全隐患部件列 服务实现类
 *
 * @author mr.wei
 * @since 2024-04-10
 */
@Slf4j
@Service
public class HazardUnitServiceImpl extends ServiceImpl<HazardUnitMapper, HazardUnit> implements HazardUnitService {

    @Autowired
    private HazardUnitMapper hazardUnitMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean addHazardUnit(HazardUnitDto dto) {
        HazardUnit hazardUnit = new HazardUnit();
        BeanUtils.copyProperties(dto, hazardUnit);
        return save(hazardUnit);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateHazardUnit(HazardUnitDto dto) {
        Long id = dto.getId();
        HazardUnit hazardUnit = getById(id);
        if (hazardUnit == null) {
            throw new BusinessException("设备安全隐患部件列不存在");
        }
        BeanUtils.copyProperties(dto, hazardUnit);
        return updateById(hazardUnit);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteHazardUnit(Long id) {
        return removeById(id);
    }

    @Override
    public HazardUnitVo getHazardUnitById(Long id) {
        return hazardUnitMapper.getHazardUnitById(id);
    }

    @Override
    public Paging<HazardUnitVo> getHazardUnitPage(HazardUnitQuery query) {
        OrderMapping orderMapping = new OrderMapping();
        orderMapping.put("createTime", "create_time");
        PagingUtil.handlePage(query, orderMapping, OrderByItem.desc("id"));
        List<HazardUnitVo> list = hazardUnitMapper.getHazardUnitPage(query);
        Paging<HazardUnitVo> paging = new Paging<>(list);
        return paging;
    }

}
